package com.xuanjia.smart_interview.sentinal;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

public class SentinalTest {


    public static void main(String[] args) {
        //配置规则
        initFlowRules();
        while (true){
            try (Entry entry = SphU.entry("HelloWorld")) {
                //被保护的逻辑
                System.out.println("helloworld");
            }catch (BlockException exception){
                //处理被流控的逻辑
                System.out.println("blocked!");
            }
        }
    }

    public static void initFlowRules()
    {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource("HelloWorld");
        //set max qps to 20
        rule1.setCount(20);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }
}
